package zuel.innovation.disley.interceptor;

import cn.fabrice.common.constant.BaseConstants;
import cn.fabrice.common.pojo.BaseResult;
import com.jfinal.aop.Aop;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import zuel.innovation.disley.common.module.Token;
import zuel.innovation.disley.user.service.UserSessionService;

public class AuthInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation invocation) {
        Controller controller=invocation.getController();
        if(!StrKit.isBlank(controller.getHeader(BaseConstants.TOKEN_NAME))){
            String token=controller.getHeader(BaseConstants.TOKEN_NAME);
            UserSessionService tokenService= Aop.get(UserSessionService.class);
            Token userToken= CacheKit.get(BaseConstants.ACCOUNT_CACHE_NAME,token,()->tokenService.getByToken(token));
            if(tokenService==null){
                controller.renderJson(BaseResult.illegal());
                return;
            }
            controller.setAttr(BaseConstants.ACCOUNT,userToken);
            controller.setAttr(BaseConstants.ACCOUNT_ID,userToken.getUId());
            invocation.invoke();
            return;
        }
    }
}
